<?php
namespace classlib\session;
class redis extends \SessionHandler {
	const SESSION_PREFIX = 'SS.php.';
	/**
	 * 存储介质Redis
	 * @var \Redis
	 */
	private $redis;
	
	/**
	 * 生成Redis session对象实例信息
	 * @param \Redis $redis
	 */
	public static function start($redis) {
		session_set_save_handler(new self($redis), true);
		session_start();				
	}
	
	/**
	 * 构造函数初始化存储介质
	 * @param unknown $redis
	 */
	public function __construct($redis) {
		$this->redis = $redis;
	}

	/**
	 * 获取Redis资料信息
	 * {@inheritDoc}
	 * @see SessionHandler::read()
	 */
	public function read($id) {
		$skey = self::SESSION_PREFIX.$id;
		$data = $this->redis->get($skey);
		return $data? $data:'';
	}

	/**
	 * 将数据存储到Redis当中
	 * {@inheritDoc}
	 * @see SessionHandler::write()
	 */
	public function write($id, $data) {
		$skey = self::SESSION_PREFIX.$id;
		$expire = ini_get('session.gc_maxlifetime');
		($expire < 0) && $expire = -1;
		$this->redis->setex($skey, $expire, $data);
	}

	/**
	 * 销毁session信息
	 * {@inheritDoc}
	 * @see SessionHandler::destroy()
	 */
	public function destroy($id) {
		$skey = self::SESSION_PREFIX.$id;
		$this->redis->del($skey);
	}
}

